package com.zpark.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zpark.entity.patients.Hospitals;
import com.zpark.service.HospitalsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/api/hospitals")
public class HospitalsController {

    @Autowired
    private HospitalsService hospitalsService;

    @GetMapping("/all")
    public List<Hospitals> getAllHospitals() {
        return hospitalsService.getAllHospitals();
    }

    @GetMapping("/levels")
    public List<String> getHospitalLevels() {
        return hospitalsService.getAllHospitals().stream()
            .map(Hospitals::getLevel)
            .distinct()
            .collect(Collectors.toList());
    }

    @GetMapping("/departments")
    public List<String> getHospitalDepartments() {
        return hospitalsService.getAllHospitals().stream()
            .flatMap(hospital -> {
                try {
                     // departments 是 JSON 数组字符串
                    List<String> depots = new ObjectMapper().readValue(
                        hospital.getDepartments(),
                        new TypeReference<List<String>>() {});
                    return depots.stream();
                } catch (Exception e) {
                    return Stream.empty();
                }
            })
            .distinct()
            .collect(Collectors.toList());
    }
}